const express = require('express')
const errorHelper = require('../util/errorHelper')
const accountController = require('../controller/accountController')
const validate = require('express-validation')
const validation = require('../validation')

const userRouter = express.Router()
const defaultShopAvatar = 'http://p6suk2a3h.bkt.clouddn.com/defaultAvatar.png'

userRouter.post('/signup', async (req, res, next) => {
  const { email, password, confirmPass } = req.body
  if (confirmPass !== password) {
    errorHelper(400, 'confirmPass not same with password')
  }
  try {
    const avatar = defaultShopAvatar
    const userId = await accountController.createAccount({
      type: 'user',
      email,
      password,
      avatar
    })
    const result = {
      status: 200,
      msg: '注册成功',
      data: {
        userId
      }
    }
    res.json(result)
  } catch (e) {
    // 如果error没有status字段说明是数据库抛出的错误，同一处理为服务器错误
    next(e)
  }
})
userRouter.post('/login', validate(validation.shopLogin), async (req, res, next) => {
  const { identityType, identifier, password } = req.body
  const device = req.headers['user-agent']
  const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress
  try {
    const { accountDetail, token } = await accountController.login({
      type: 'user',
      identityType,
      identifier,
      password,
      device,
      ip
    })
    res.json({
      status: 200,
      msg: '登录成功',
      data: {
        userDetail: accountDetail,
        token
      }
    })
  } catch (e) {
    next(e)
  }
})
module.exports = userRouter
